from django.shortcuts import render
from django.views.generic.base import TemplateView
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Book, Author, BookAuthor
from django.contrib.postgres.search import SearchVector
# Create your views here.


class HomeView(TemplateView):
    template_name = 'book/home.html'
    # model = Book
    # paginate_by = 10

    # def get_queryset(self):
    #     contacts = Contact.objects.annotate(order_count=Count('orders')
    #     queryset = super(IndexView, self).get_queryset()
    #     queryset = queryset.annotate(order_count=Count('orders'), order_sum=Sum('orders'))
    #     queryset = queryset.prefetch_related(Prefetch('contacts', queryset=contacts))
    #     return queryset
    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        q = self.request.GET.get('q', None)
        if q:
            #book_list = Book.objects.filter(slug__contains=q).order_by('-id')
            #book_list = Book.objects.prefetch_related('authors').prefetch_related('tags').annotate(search=SearchVector('title','sub_title')).filter(search=q).order_by('-id')
            book_list = Book.objects.prefetch_related('authors').prefetch_related('tags').filter(bookindex__tsv = q).order_by('-id')
        else:
            book_list = Book.objects.prefetch_related('authors').prefetch_related('tags').order_by('-id').all()
        paginator = Paginator(book_list, 10)

        page = self.request.GET.get('page')
        try:
            books = paginator.page(page)
        except PageNotAnInteger:
            books = paginator.page(1)
        except EmptyPage:
            books = paginator.page(paginator.num_pages)

        # book_authors = BookAuthor.objects.select_related(
        #     'author').filter(book__in=books.object_list)
        for book in books.object_list:
            #book.authors = [ba for ba in book_authors if ba.book == book]
            if not book.cover_url.startswith('http'):
                book.cover_local_url = book.cover_url
        context['books'] = books
        context['q'] = q or ''
        return context


class AuthorView(TemplateView):
    template_name = 'book/author.html'

    def get_context_data(self, **kwargs):
        context = super(AuthorView, self).get_context_data(**kwargs)
        author = Author.objects.get(slug=kwargs['slug'])
        author.books = []
        for x in author.bookauthor_set.all():
            author.books.append(x.book)
        book_authors = BookAuthor.objects.select_related(
            'author').filter(book__in=author.books)
        for book in author.books:
            #book.authors = [ba for ba in book_authors if ba.book == book]
            if not book.cover_url.startswith('http'):
                book.cover_local_url = book.cover_url
        context['author'] = author
        return context


class ItemView(TemplateView):
    template_name = 'book/item.html'

    def get_context_data(self, **kwargs):
        context = super(ItemView, self).get_context_data(**kwargs)
        book = Book.objects.prefetch_related('authors').get(slug=kwargs['slug'])
        book.formats = []
        if not book.cover_url.startswith('http'):
            book.cover_local_url = book.cover_url
        for x in book.booksource_set.all():
            book.formats.extend(x.bookdownloadurl_set.all())
        #book.authors = BookAuthor.objects.filter(book=book).all()
        context['book'] = book
        return context


class DemoView(TemplateView):
    template_name = 'book/demo.html'

    def get_context_data(self, **kwargs):
        context = super(DemoView, self).get_context_data(**kwargs)
        print(kwargs)
        return context
